from flask import Blueprint,request,jsonify
from db import db1
from utils.acl import acl
import json
from utils.rs import rs
from utils.jwtc import myjwt
from utils.myfile import get_data
import time
bp_user = Blueprint('user',__name__)

@bp_user.route('/login',methods=['GET','POST'])
def login():
    data = get_data()
    # 用户账号与密码
    username = data['username']
    password = data['password']
    # 判断用户名与密码是否正确
    sql = "select * from users where username='{}' and password='{}'".format(username,password)
    res = db1.find(sql)
    if not res:
        # 不存在直接返回
        return jsonify({'code':200,'msg':'用户名或密码错误,请重新输入'})
    starttime = time.time()
    # 生成token
    data = {'data': {"username": res['username'], 'uid': res['id'], "iat": starttime, "exp": 3600}}
    token = myjwt.jwt_en(data)
    # 获取用户页面权限
    pagelist = acl.get_page_reslist(res['id'])
    # 获取接口页面权限
    interfacelist = acl.get_interface_relist(res['id'])
    key = 'interfacelist'+str(res['id'])
    rs.insert_set(key,interfacelist)
    return jsonify({'code':200,'token':token,'pagelist':pagelist,'userid':res['id'],'username':res['username']})

@bp_user.route('/roleM')
def roleM():
    return 'rolem'


@bp_user.route('/test')
def test():
    return 'test'


def getresdata(data):
    # 把顶级拿出来放到列表中
    list = []
    idlist=[]
    for i in data:
        id = i['pid']
        if id not in idlist:
            list.append({'id':id,'name':i['pname'],'son':[]})
            idlist.append(id)
    # 变理顶级列表，在遍历数据，把子类加到顶级列表
    for j,value in enumerate(list):
        for i in data:
            if value['id'] == i['pid']:
                list[j]['son'].append({'id':i['id'],'name':i['name'],'url':i['url']})
    return list



@bp_user.route('/getResource')
def getResource():
    uid = 1
    res = acl.get_resource(uid)
    mes = getresdata(res)
    return jsonify({'list':mes})
